package com.itat.client;

import com.itat.protocol.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



/**
 * 重试连接板
 * client消息处理类
 * @author baixuefeng
 * @date 2021-12-29
 */
public class ReconnectClientHandler extends SimpleChannelInboundHandler<RpcResponse> {

    private static final Log log = LogFactory.getLog(ReconnectClientHandler.class);


    private final int retryConnectTime = 10;//s

    private ReconnectClient client;
    public ReconnectClientHandler(ReconnectClient client) {
        this.client = client;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //此处连接失败重连
        super.channelInactive(ctx);
        //重试时间
        log.info("netty客户断线重连...try to connect after 10s");
        Thread.sleep(retryConnectTime);
        client.doConnect(retryConnectTime);

    }





    /**
     * 处理服务端返回的数据
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse) throws Exception {
        System.out.println("netty客户端响应数据: " + rpcResponse.toString());
    }

    //处理服务端返回的数据[channelRead()优先级高于channelRead0(),可以共存]
   /* @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("client响应数据: " + msg.toString());
    }*/

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
